package com.xpec.c4.net.codec;

import java.nio.ByteBuffer;

import com.xpec.c4.service.message.BasicMessage;
import com.xpec.c4.service.message.NetMessage;
import com.xpec.c4.service.utility.JavaZip;
import com.xpec.c4.service.utility.Utility;

/**
 * 
 * 
 * @author Bany
 *
 * @since 2008-11-27 下午06:42:50
 *
 */

public class ZipCompressCodecExtend implements CodecExtend, CodecExtendEx {
	
	private static final int COMPRESS_FLAG_LENGTH = 1;

	@Override
	public ByteBuffer execute(ByteBuffer buffer, Object message) throws Exception {
		Object messageContent=((NetMessage) message).getMessageContent();
		boolean compress=false;
		
		if(messageContent instanceof BasicMessage && ((BasicMessage)messageContent).isCompress()==true){
			compress=true;
		}
		
		if(((NetMessage) message).isCompress()){
			compress=true;
		}
				
		
		//buffer.flip();

		if(compress){
			ByteBuffer temp=JavaZip.compress(buffer);
			buffer=temp;
		}
		
		ByteBuffer temp = ByteBuffer.allocate(buffer.limit()+COMPRESS_FLAG_LENGTH);
		temp.put(Utility.getBoolean(compress));
		temp.put(buffer);
		
		return temp;
	}
	
	
	@Override
	public ByteBuffer execute(ByteBuffer buffer, boolean compress) throws Exception 
	{
		if(compress){
			ByteBuffer temp=JavaZip.compress(buffer);
			buffer=temp;
		}
		
		ByteBuffer temp = ByteBuffer.allocate(buffer.limit()+COMPRESS_FLAG_LENGTH);
		temp.put(Utility.getBoolean(compress));
		temp.put(buffer);
		
		return temp;
	}

	@Override
	public ByteBuffer execute(byte[] bytes, boolean compress) throws Exception
	{
		byte[] output = bytes;
		
		if( compress )
		{
			output = JavaZip.compressBytes(bytes);
		}
		
		ByteBuffer temp = ByteBuffer.allocate(output.length+COMPRESS_FLAG_LENGTH);
		temp.put(Utility.getBoolean(compress));
		temp.put(output);
		
		return temp;
	}
	
}
